<template>
  <div class="todo-item" :class="{ completed: todo.completed }">
    <div class="todo-content">
      <input
        type="checkbox"
        :checked="todo.completed"
        @change="$emit('toggle-todo')"
        class="todo-checkbox"
      />
      
      <div class="todo-text" @dblclick="startEditing">
        <span v-if="!isEditing" class="text">{{ todo.text }}</span>
        <input
          v-else
          ref="editInput"
          v-model="editText"
          @blur="saveEdit"
          @keyup.enter="saveEdit"
          @keyup.escape="cancelEdit"
          type="text"
          class="edit-input"
        />
        <small class="todo-time">{{ todo.createdAt }}</small>
      </div>
    </div>

    <button @click="$emit('delete-todo')" class="delete-btn" title="删除">
      🗑️
    </button>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'

const props = defineProps({
  todo: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['toggle-todo', 'delete-todo', 'edit-todo'])

const isEditing = ref(false)
const editText = ref('')
const editInput = ref(null)

const startEditing = () => {
  if (!props.todo.completed) {
    isEditing.value = true
    editText.value = props.todo.text
    nextTick(() => {
      editInput.value.focus()
      editInput.value.select()
    })
  }
}

const saveEdit = () => {
  if (editText.value.trim() && editText.value !== props.todo.text) {
    emit('edit-todo', editText.value)
    isEditing.value = false
  } else {
    cancelEdit()
  }
}

const cancelEdit = () => {
  isEditing.value = false
  editText.value = props.todo.text
}
</script>